{% extends '../_manage.html' %}

{% block title %} {{ form.name }} {% endblock %}

{% block head %}

<script>
$(function () {
    getJSON('/api/categories', function (err, data) {
        if (err) {
            return showError(err);
        }
        var categories = data.categories;
        var id = '{{ id }}';
        if (id) {
            getJSON('/api/articles/' + id, function (err, article) {
                if (err) {
                    return showError(err);
                }
                initVM(article, categories);
            });
        }
        else {
            initVM({ id: '' }, categories);
        }
    });
});

function initVM(article, categories) {
    if (article.cover_id) {
        $('#image-preview').css('background-image', 'url(/files/attachments/' + article.cover_id + '/l)');
    }
    var vm = new Vue({
        el: '#vm',
        data: {
            image: null,
            categories: categories,
            name: article.name,
            description: article.description,
            category_id: article.category_id,
            tags: article.tags,
            publish_date: article.publish_at ? article.publish_at.toDate() : '',
            publish_time: article.publish_at ? article.publish_at.toTime() : '',
            content: article.content || ''
        },
        created: function () {
            $('#loading').hide();
            $('#vm').show();
        },
        methods: {
            getPostData: function () {
                var data = {
                    name: this.name,
                    description: this.description,
                    category_id: this.category_id,
                    tags: this.tags
                };
                var pubDate = findForm().find('input[name=publish_date]').val().trim();
                var pubTime = findForm().find('input[name=publish_time]').val().trim();
                if (pubDate !== '' || pubTime !== '') {
                    var ts;
                    if (pubDate === '') {
                        throw { error: 'parameter:invalid', data: 'publish_date', message: 'Invalid publish date.'};
                    }
                    if (pubTime === '') {
                        ts = Date.parse(pubDate);
                        if (isNaN(ts)) {
                            throw { error: 'parameter:invalid', data: 'publish_date', message: 'Invalid publish date.'};
                        }
                    } else {
                        ts = Date.parse(pubDate + 'T' + pubTime);
                        if (isNaN(ts)) {
                            throw { error: 'parameter:invalid', data: 'publish_time', message: 'Invalid publish time.'};
                        }
                    }
                    // adjust timezone:
                    ts = ts + (new Date()).getTimezoneOffset() * 60000;
                    data.publish_at = ts;
                }
                var content = $('#content-editor').val();
                if (this.content !== content) {
                    data.content = content;
                }
                if (this.image !== null) {
                    data.image = this.image;
                }
                return data;
            },
            submit: function () {
                var that = this;
                clearFormError();
                var data;
                try {
                    data = this.getPostData();
                }
                catch (e) {
                    showFormError(e);
                    return;
                }
                that.$resource('{{ form.action }}').save(data).then(function (resp) {
                    resp.json().then(function (result) {
                        that.saved = true;
                        location.assign('{{ form.redirect }}');
                    });
                }, onJsonFormError);
            }
        }
    });

    // check content when unload:
    window.onbeforeunload = function() {
        if (vm.saved) {
            return;
        }
        if (vm.content !== $('#content-editor').val()) {
            return "{{ _('Content has been changed.') }}";
        }
    };

    // fix vue select init:
//    $('select[name=category_id]').val(article.category_id || '');

    $('#content-editor').val(article.content || '');
    var htmleditor = UIkit.htmleditor($('#content-editor').get(0), {
        markdown: true,
        maxsplitsize: 600
    });
    window.htmleditor = htmleditor;

    // watch file change:
    $('#file').change(function (evt) {
        evt.preventDefault();
        var f = $('#file').val();
        if (f === '') {
            // user cancelled selected file:
            vm.image = null;
            $('#image-preview').css('background-image', 'none');
            return;
        }
        try {
            var file = $('#file').get(0).files[0];
            processImageFile(file, function (r) {
                vm.image = r.data;
                $('#image-preview').css('background-image', 'url(' + r.image + ')');
            });
        }
        catch (e) {
            UIkit.modal.alert('Error when process file: ' + e);
        }
    });
}

</script>

{% endblock %}

{% block main %}

    <div id="loading" class="uk-width-1-1">
        <i class="uk-icon-spinner uk-icon-spin"></i> {{ _('Loading') }}...
    </div>

    <div id="vm" class="uk-width-1-1">
        <ul class="uk-tab" data-uk-tab>
            <li class="uk-active"><a href="#0">{{ _('Articles') }}</a></li>
            <li><a href="#0" onclick="location.assign('/manage/article/category_list')">{{ _('Categories') }}</a></li>
        </ul>

        <form v-on:submit.prevent="submit" class="uk-form uk-form-stacked uk-margin">
            <legend>{{ _(form.name) }}</legend>
            <fieldset>
                <div class="uk-alert uk-alert-danger uk-hidden"></div>
                <div class="uk-form-row">
                    <label class="uk-form-label">Image:</label>
                    <div class="uk-form-controls">
                        <div id="image-preview" style="border: 1px solid #ccc; width:642px; height:362px; background-size:cover;"></div>
                    </div>
                    <div class="uk-form-controls">
                        <input id="file" type="file">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="uk-form-label">{{ _('Name') }}:</label>
                    <div class="uk-form-controls">
                        <input v-model="name" name="name" type="text" maxlength="100" class="uk-width-1-1" placeholder="name">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="uk-form-label">Description:</label>
                    <div class="uk-form-controls">
                        <textarea v-model="description" name="description" rows="6" class="uk-width-1-1" style="resize:none;"></textarea>
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="uk-form-label">{{ _('Category') }}:</label>
                    <div class="uk-form-controls">
                        <select v-model="category_id" name="category_id" class="uk-width-1-1">
                            {% raw %}
                            <option v-for="category in categories" v-bind:value="category.id" v-text="category.name"></option>
                            {% endraw %}
                        </select>
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="control-label">Tags:</label>
                    <div class="controls">
                        <input v-model="tags" name="tags" type="text" class="uk-width-1-1" placeholder="tag1, tag2, tag3">
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="control-label">Publish At:</label>
                    <div class="controls">
                        <input v-once v-model="publish_date" name="publish_date" type="text" class="uk-width-1-6" data-uk-datepicker="{format:'YYYY-MM-DD', i18n:{ months:['{{ _('January') }}' , '{{ _('February') }}' , '{{ _('March') }}' , '{{ _('April') }}' , '{{ _('May') }}' , '{{ _('June') }}' , '{{ _('July') }}' , '{{ _('August') }}' , '{{ _('September') }}' , '{{ _('October') }}' , '{{ _('November') }}' , '{{ _('December') }}'], weekdays:['{{ _('Sun') }}' , '{{ _('Mon') }}' , '{{ _('Tue') }}' , '{{ _('Wed') }}' , '{{ _('Thu') }}' , '{{ _('Fri') }}' , '{{ _('Sat') }}'] } }">
                        <input v-once v-model="publish_time" name="publish_time"type="text" data-uk-timepicker>
                    </div>
                </div>
                <div class="uk-form-row">
                    <label class="control-label">Content:</label>
                    <div class="controls">
                        <textarea id="content-editor" name="content" rows="20" style="width:100%; resize:none;"></textarea>
                    </div>
                </div>
                <div class="uk-form-row">
                    <div class="controls">
                        <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-check"></i> Save</button>
                        <button type="button" class="uk-button" onclick="location.assign('{{ form.redirect }}')"><i class="uk-icon-times"></i> Cancel</button>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>

{% endblock %}
